package com.example.book.common.configs;

import com.example.book.common.annotation.LoginIgnore;
import com.example.book.common.exception.ApiLoginException;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.common.utils.SpringUtils;
import com.example.book.domain.wx.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 后台登录拦截器
 * @author haocjia
 */
public class LoginInterceptor implements HandlerInterceptor {

    private final static String AJAX = "XMLHttpRequest";
    private final static String LOGINPATH = "/login";
    private final static String API_URl = "/api";

    private RedisService redisService = SpringUtils.getBean("redisService");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = AJAX.equals(header);
        if (isAjax && session.getAttribute(Constants.CURRENT_USER) == null) {
            response.setHeader("REDIRECT", "REDIRECT");
            response.setHeader("CONTEXTPATH", LOGINPATH);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        return true;
    }


}
